package com.sport.apis.interceptor;


import com.sport.common.redis.CacheService;
import com.sport.common.redis.RedisKey;
import com.sport.model.user.bos.AccountUserBo;
import com.sport.utils.common.AppJwtUtil;
import com.sport.utils.common.BaseUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.Map;

@Slf4j
@Component
public class GlobalInterceptor implements HandlerInterceptor {

    @Resource
    private CacheService cacheService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info(request.getRequestURL() + " ");
        //获取token
        String token = request.getHeader("token");

        //可能会解析失败
        Claims claims = AppJwtUtil.getClaimsBody(token);
        if (claims == null) {
            log.warn("token不存在！无法解析！请用户重新登陆！");
            return false;
        }

        String schoolTenementId = String.valueOf(claims.get("id"));

        Map<String, Object> parameterMaps = BaseUtils.secondMapPutIntoFirstMap(
                BaseUtils.quickCreateMap("schoolTenementId", schoolTenementId)
                , cacheService.getMap(RedisKey.USER_INFORMATION + schoolTenementId)
        );

        if (parameterMaps == null) {
            log.warn("已过期！请重新登陆！");
            return false;
        }

        AccountUserBo accountUserBo = BaseUtils.mapToObjectConverter(parameterMaps, AccountUserBo.class);

        if (accountUserBo == null) {
            log.warn("该用户未登录！");
            return false;
        }
        //保存租户id
        return AccountUserBo.saveUser(accountUserBo);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        AccountUserBo.clear();
    }


}
